import {
  createRouter,
  createWebHashHistory,
  isNavigationFailure,
  RouteRecordRaw,
} from "vue-router";
import nprogress from "nprogress";
import "nprogress/nprogress.css";
const routes: Array<RouteRecordRaw> = [
  {
    name: "Home",
    path: "/",
    component: () =>
      import(/* webpackChunkName:'home' */ "@/views/home/index.vue"),
    meta: {
      title: "Home",
    },
    children: [
      {
        name: "Meter",
        path: "/meter",
        component: () =>
          import(
            /* webpackChunkName:'meter' */ "@/views/pages/meter/index.vue"
          ),
        meta: {
          title: "Meter",
        },
      },
    ],
  },
  {
    name: "Error",
    path: "/:catchAll(.*)",
    component: () => import(/* webpackChunkName:'404' */ "@/views/404.vue"),
    meta: {
      title: "404",
    },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  console.warn("[beforeEach]", to, from);
  nprogress.start();
  const token = window.localStorage.getItem("Token");
  if (!/^\/login/.test(to.fullPath) && !token) {
    next({
      name: "Login",
      query: { source: encodeURIComponent(location.href) },
    });
  } else {
    next();
  }
});

router.afterEach((to, from, failure) => {
  console.warn("[afterEach]", to, from);
  nprogress.done();
  const docTitle = document.getElementsByTagName("title")[0];
  docTitle.innerHTML = to.meta.title + "";
  if (isNavigationFailure(failure)) {
    console.error(failure);
  }
});

export default router;
